package com.ncui.wisdomLearn.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ncui.wisdomLearn.api.entity.User;
import com.ncui.wisdomLearn.biz.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * MyBatis-Plus 自动填充处理器
 *
 * @author lvlele
 * @since 2025-01-08
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("start insert fill ....");
        // 创建时间
        this.strictInsertFill(metaObject, "createTime", Date::new, Date.class);
        // 更新时间
        this.strictInsertFill(metaObject, "updateTime", Date::new, Date.class);
        // 创建人（从当前登录用户中获取）
        this.strictInsertFill(metaObject, "createBy", this::getCurrentUsername, String.class);
        // 更新人（从当前登录用户中获取）
        this.strictInsertFill(metaObject, "updateBy", this::getCurrentUsername, String.class);
        // 删除标记默认值
        this.strictInsertFill(metaObject, "delFlag", () -> false, Boolean.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("start update fill ....");
        // 更新时间
        this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);
        // 更新人（从当前登录用户中获取）
        this.strictUpdateFill(metaObject, "updateBy", this::getCurrentUsername, String.class);
    }

    /**
     * 获取当前登录用户名
     * 如果用户未登录，则返回 "system"
     *
     * @return 当前登录用户名
     */
    private String getCurrentUsername() {
        try {
            if (StpUtil.isLogin()) {
                Long userId = StpUtil.getLoginIdAsLong();
                // 延迟获取 UserService，避免循环依赖
                UserService userService = applicationContext.getBean(UserService.class);
                User user = userService.getById(userId);
                if (user != null) {
                    return user.getUsername() != null ? user.getUsername() : user.getEmail();
                }
            }
        } catch (Exception e) {
            log.warn("获取当前登录用户信息失败", e);
        }
        return "system";
    }
} 